package com.lyc.wanandroid_kotlin.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.lyc.wanandroid_kotlin.constant.Constant
import com.lyc.wanandroid_kotlin.event.NetworkChangeEvent
import com.lyc.wanandroid_kotlin.utils.NetWorkUtil
import com.lyc.wanandroid_kotlin.utils.Preference
import org.greenrobot.eventbus.EventBus

/**
 * ClassName:com.lyc.wanandroid_kotlin.receiver
 * Description:
 */
@Suppress("DEPRECATION")
class NetworkChangeReceiver : BroadcastReceiver() {

    /**
     * 缓存上一次的网络状态
     */
    private var hasNetwork: Boolean by Preference(Constant.HAS_NETWORK_KEY, true)


    override fun onReceive(context: Context?, intent: Intent?) {
        val isConnected = NetWorkUtil.isNetworkConnected(context)

        if (isConnected) {
            if (isConnected != hasNetwork) {
                EventBus.getDefault().post(NetworkChangeEvent(isConnected))
            }
        } else {
            EventBus.getDefault().post(NetworkChangeEvent(isConnected))
        }
    }
}
